<template>
  <div>
    <NavBar></NavBar>
    <div class="question-container">
      <div class="question-header">
        <h2><el-tag type="primary">{{modularName}}</el-tag>&nbsp;&nbsp;{{questionName}}</h2>
        <div>
          <span>
            <el-button type="primary" plain icon="el-icon-edit" @click="toEdit" v-if="!isEdit">写回答</el-button>
            <el-button type="primary" plain icon="el-icon-edit" @click="toEdit" v-if="isEdit">收起</el-button>
          </span>
          <span>
            <i class="el-icon-chat-line-round">{{answerNum}}条回答</i>
          </span>
        </div>
      </div>
    </div>
    <div class="body">
      <div class="edit-container" v-show="isEdit">
        <div id="toolbar" class="toolbar"></div>
        <div id="editor"></div>
        <br>
        <div class="dialog-footer">
          <el-button type="primary" @click="addAnswer">提交</el-button>
        </div>
      </div>
      <div class="answer-container" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="1">
        <div class="answer-content" v-for="(item, index) in answerList" :key="index">
          <div class="answer-head" @click="toUserDetail(item.userId)">
            <span class="img-area">
              <img :src="item.avatar" alt="" width="40px" height="40px">
            </span>
            <span class="name-area">
              {{item.userName}}
            </span>
          </div>
          <div class="answer-body">
            <p v-html="item.answerMessage"></p>
          </div>
          <div class="answer-footer">
            <span>
              <el-button type="primary" icon="el-icon-caret-top" @click="userLike(item.id,item.userId)" v-show="!item.like">赞同{{item.likeCount}}</el-button>
              <el-button type="primary" icon="el-icon-caret-top" disabled v-show="item.like">已赞同{{item.likeCount}}</el-button>
            </span>
            <span>
              <el-button type="danger" icon="el-icon-caret-bottom" @click="userUnlike(item.id,item.userId)" v-show="!item.like" disabled></el-button>
              <el-button type="danger" icon="el-icon-caret-bottom" @click="userUnlike(item.id,item.userId)" v-show="item.like"></el-button>
            </span>
            <span>
              <el-button type="success"  icon="el-icon-collection-tag" @click="userCollect(item.id,item.userId)" v-show="!item.collect">收藏</el-button>
              <el-button type="success" icon="el-icon-collection-tag" disabled v-show="item.collect">已收藏</el-button>
            </span>
            <span class="comment-btn">
              <!-- <el-button type="primary" icon="el-icon-document">{{item.commentCount}}条评论</el-button> -->
              <span type="primary"><i class="el-icon-document"></i>{{item.commentCount}}条评论</span>
            </span>
          </div>
          <div class="comment-container">
            <div class="comment-head">
              <span>评论 ({{item.commentCount}})</span>
            </div>
            <div class="comment-body" v-for="(i, index2) in item.commentList" :key="index2">
              <div class="comment-item1">
                <span class="comment-avatar">
                  <img :src="i.avatar" alt="">
                </span>
                <span class="comment-username">{{i.username}}</span>
                <span class="comment-time">{{i.timeAgoStr}}</span>
              </div>
              <div class="comment-item2">
                {{i.comment}}
              </div>
            </div>
            <div class="add-comment">
              <div class="add1">
                <el-input v-model="comment" placeholder="添加你的评论"></el-input>
              </div>
              <div class="add2"><el-button type="success" plain @click="addComment(item.id)">提交</el-button></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar'
import axios from 'axios'
import Editor from 'wangeditor'
import 'wangeditor/release/wangEditor.min.css'
var editor = new Editor('#toolbar', '#editor')
export default {
  name: 'AnswerDetail',
  components: {
    NavBar
  },
  data () {
    return {
      comment: '',
      isEdit: false,
      answerList: [],
      questionName: '',
      page: 1,
      finalPage: 1,
      busy: false,
      answerNum: '',
      commentDialog: false,
      modularName: '',
      commentData: {
        userId: '',
        comment: '',
        answerId: ''
      },
      formData: {
        questionId: '',
        userId: '',
        answerMessage: ''
      },
      userId: localStorage.getItem('userId')
    }
  },
  created () {
    this.showAnswerList(this.page)
    this.showNum()
  },
  mounted () {
    editor.customConfig.menus = [
      'head', // 标题
      // 'bold', // 粗体//'italic', // 斜体//'underline', // 下划线//'strikeThrough', // 删除线//'foreColor', // 文字颜色//'backColor', // 背景颜色
      'link', // 插入链接
      // 'list', // 列表
      'justify', // 对齐方式
      // 'emoticon', // 表情
      'image', // 插入图片
      'table', // 表格//'video', // 插入视频//'code', // 插入代码//'quote', // 引用
      'undo', // 撤销
      'redo' // 重复
    ]
    // 上传图片
    editor.customConfig.uploadImgTimeout = 20000
    editor.customConfig.uploadImgMaxSize = 20 * 1024 * 1024
    editor.customConfig.uploadImgServer = ''
    editor.customConfig.uploadFileName = 'image'
    editor.customConfig.withCredentials = true
    editor.customConfig.uploadImgParams = {
      type: 'email'
    }
    editor.customConfig.onchange = html => {
      this.formData.answerMessage = html
    }
    editor.customConfig.uploadImgHooks = {
      success: function (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
      },
      fail: function (xhr, editor, result) {
        // 图片上传并返回结果，但图片插入错误时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
      },
      error: function (xhr, editor) {
        // 图片上传出错时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },
      timeout: function (xhr, editor) {
        // 图片上传超时时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },

      // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
      // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
      customInsert: function (insertImg, result, editor) {
        console.log(result)
        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        var url = result.data.path
        insertImg(url)

        // result 必须是一个 JSON 格式字符串！！！否则报错
      }
    }
    // 自定义上传事件
    editor.customConfig.hideLinkImg = true
    editor.create()
  },
  methods: {
    loadMore () {
      if (this.finalPage > this.page) {
        this.busy = true
        this.page++
        this.showLike(this.page)
        setTimeout(() => {
        // 这里请求接口去拿数据，实际应该是调用一个请求数据的方法
          this.busy = false
        }, 1000)
      } else {
        this.busy = false
      }
    },
    handleCommentDialog () {
      this.commentDialog = true
      console.log(this.commentDialog)
    },
    toUserDetail (id) {
      this.$router.push('/user-detail?id=' + id)
    },
    showAnswerList (page) {
      const creator = this.$route.query.creator
      let url = ''
      if (creator) {
        url = '/api/answer/queryAnswerList?page=' + page + '&questionId=' + this.$route.query.id + '&loginUserId=' + this.userId + '&userId=' + creator
      } else {
        url = '/api/answer/queryAnswerList?page=' + page + '&questionId=' + this.$route.query.id + '&loginUserId=' + this.userId
      }
      axios.get(url).then(res => {
        const resData = res.data.data.pagedResult.rows
        this.finalPage = res.data.data.pagedResult.total
        this.answerList = page === 1 ? resData : this.answerList.concat(resData)
        this.answerList.map(item => {
          item.avatar = 'http://127.0.0.1:9901' + item.avatar
          item.commentList.map(i => {
            i.avatar = 'http://127.0.0.1:9901' + i.avatar
          })
        })
        this.questionName = res.data.data.qvo.questionName
        this.modularName = res.data.data.qvo.modularName
      }).catch(err => {
        console.log(err)
      })
    },
    showNum () {
      axios.get('/api/answer/showNum?qid=' + this.$route.query.id).then(res => {
        this.answerNum = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    toEdit () {
      this.isEdit = !this.isEdit
    },
    userLike (answerId, creatorId) {
      const url = '/api/answer/userLike?userId=' + this.userId + '&answerId=' + answerId + '&creatorId=' + creatorId + '&status=' + 0
      axios.get(url).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.showAnswerList(this.page)
      }).catch(err => {
        console.log(err)
      })
    },
    userUnlike (answerId, creatorId) {
      this.$confirm('确定取消点赞？').then(() => {
        const url = '/api/answer/userUnlike?userId=' + this.userId + '&answerId=' + answerId + '&creatorId=' + creatorId
        axios.get(url).then(res => {
          this.$notify({
            title: '成功',
            message: res.data.data,
            type: 'success'
          })
          this.showAnswerList(this.page)
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {

      })
    },
    userCollect (answerId, creatorId) {
      const url = '/api/answer/userLike?userId=' + this.userId + '&answerId=' + answerId + '&creatorId=' + creatorId + '&status=' + 1
      axios.get(url).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.showAnswerList(this.page)
      }).catch(err => {
        console.log(err)
      })
    },
    addAnswer () {
      this.formData.questionId = this.$route.query.id
      this.formData.userId = localStorage.getItem('userId')
      axios.post('/api/answer/addAnswer', this.formData).then(res => {
        console.log(res)
        this.$notify({
          title: '成功',
          message: '发布成功',
          type: 'success'
        })
        this.formData.answerMessage = ''
        this.isEdit = false
        this.showAnswerList(this.page)
        this.showNum()
      }).catch(err => {
        console.log(err)
      })
    },
    addComment (aid) {
      // console.log(index)
      this.commentData.userId = localStorage.getItem('userId')
      this.commentData.comment = this.comment
      this.commentData.answerId = aid
      axios.post('/api/answer/addComment', this.commentData).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.comment = ''
        this.showAnswerList(1)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.question-container {
  width: 100%;
  background: #fff;
  padding-top: 80px;
  box-shadow: 0 1px 3px rgba(26,26,26,.1);
  padding-bottom: 10px;
  .question-header {
    width: 60%;
    margin: 0 auto;
  }
}
.body{
  width: 100%;
  min-height: 1000px;
  height: auto;
  padding: 10px;
  background: #efefef;
  .edit-container {
    width: 70%;
    height: auto;
    margin: 0 auto;
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    margin-bottom: 10px;
    #toolbar {
      width: 92%;
      margin-left: 4%;
      background: white;
      position: absolute;
      border-radius: 5px 5px 0 0;
    }

    #editor {
      width: 100%;
      padding-top: 30px;
    }
  }
  .answer-container {
    width: 70%;
    height: auto;
    margin: 0 auto;
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    .answer-content {
      padding: 10px;
      border-bottom: 1px #efefef solid;
      .answer-head {
        width: 100%;
        line-height: 40px;
        .img-area {
          display: inline-block;
          width: 40px;
          height: 40px;
          background: #efefef;
        }
        .name-area {
          font-size: 18px;
          font-weight: bold;
        }
      }
      .answer-footer {
        .comment-btn {
          float:right;
        }
      }
      .comment-container {
        width: 100%;
        margin: 0 auto;
        margin-top: 10px;
        box-shadow: 0 1px 3px rgba(26,26,26,.1);
        border: 1px solid #ebebeb;
        border-radius: 4px;
        .comment-head {
          padding: 20px;
          border-bottom: 1px solid #f6f6f6;
        }
        .comment-body {
          border-bottom: 1px solid #efefef;
          .comment-item1 {
            height: 60px;
            line-height: 60px;
            padding: 10px;
            border-bottom: 1px solid #f6f6f6;
            .comment-avatar{
              img {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background: #efefef;
                vertical-align: top;
              }
            }
            .comment-time {
              float: right;
              font-size: 14px;
              color: #8590a6;
            }
          }
          .comment-item2 {
            padding: 10px;
          }
        }
        .add-comment {
          width: 100%;
          padding: 10px;
          display: flex;
          .add1 {
            width: 80%;
          }
          .add2 {
            width: 10%;
            position: relative;
            left: 20px;
          }
        }
      }
    }
  }
}

</style>
